package mrpanyu.guitool.dbcodegen.processor;

import java.util.ArrayList;
import java.util.List;

import mrpanyu.guitool.dbcodegen.model.Database;
import mrpanyu.guitool.dbcodegen.model.ForeignKey;
import mrpanyu.guitool.dbcodegen.model.Table;

/**
 * 给<code>ForeignKey</code>对象设置额外属性：referanceTable - 引用的Table对象
 * <p>
 * 给<code>Table</code>对象设置额外属性：referers - 有外键关联的表对象
 * 
 */
public class ForeignKeyReferenceSetter implements DbModelProcessor {

	@SuppressWarnings("unchecked")
	@Override
	public Database process(Database model) throws Exception {
		for (Table table : model.getTables()) {
			table.setExtProperty("referers", new ArrayList<Table>());
		}
		for (Table table : model.getTables()) {
			for (ForeignKey fk : table.getForeignKeys()) {
				String refTableName = fk.getReferenceTableName();
				Table refTable = findTable(model, refTableName);
				fk.setExtProperty("referenceTable", refTable);
				List<Table> referers = (List<Table>) refTable.getExtProperty("referers");
				referers.add(table);
			}
		}
		return model;
	}

	private Table findTable(Database model, String tableName) throws Exception {
		Table table = null;
		for (Table t : model.getTables()) {
			if (tableName.equals(t.getTableName())) {
				table = t;
				break;
			}
		}
		return table;
	}

}
